package comoabejas

import org.springframework.core.io.ClassPathResource
import org.springframework.core.io.Resource

class DealController {
	//def beforeInterceptor = [action:this.&checkUser,only:['comprar']]
	def dealService;
	def imageService;
	def userService;
	def areaService;
	def clientService
	def purchaseService
	
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
    	dealService.listObj();
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        
         render(view: "list", model: [dealInstanceList: Deal.list(params), dealInstanceTotal: Deal.count()])
         
    }

    def create = {
        def dealInstance = new Deal()
        dealInstance.properties = params
        render(view: "create", model: [dealInstance: dealInstance])

        //return [dealInstance: dealInstance]
    }

    def save = {
    	
    	
        def dealInstance = new Deal(params)
		
		//def image = new Image()
		def image = new Imagen();
		image.properties = params['myFile']
		
		                          
		image = imageService.saveObj(image);
        
		dealInstance.image = image
		dealInstance.setCurrentNumberOfUsers 0
		dealInstance = dealService.saveObj(dealInstance)
		
        if (dealInstance!=null) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'deal.label', default: 'Deal'), dealInstance.id])}"
            redirect(action: "show", id: dealInstance.id)
        }
        else {
            render(view: "create", model: [dealInstance: dealInstance])
        }
    }

    def show = {
        def dealInstance = Deal.get(params.id)
        if (!dealInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])}"
            redirect(action: "list")
        }
        else {
            [dealInstance: dealInstance]
        }
    }

    def edit = {
        def dealInstance = Deal.get(params.id)
        if (!dealInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [dealInstance: dealInstance,dealStates:DealState.getList()]
        }
    }

    def update = {
        def dealInstance = Deal.get(params.id)
        if (dealInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (dealInstance.version > version) {
                    
                    dealInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'deal.label', default: 'Deal')] as Object[], "Another user has updated this Deal while you were editing")
                    render(view: "edit", model: [dealInstance: dealInstance])
                    return
                }
            }
            dealInstance.properties = params
            if (!dealInstance.hasErrors() && dealInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'deal.label', default: 'Deal'), dealInstance.id])}"
                redirect(action: "show", id: dealInstance.id)
            }
            else {
                render(view: "edit", model: [dealInstance: dealInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        //def dealInstance = Deal.get(params.id)
        def dealInstance = dealService.getObj(params.id)

        if (dealInstance) {
            try {
                //dealInstance.delete(flush: true)
            	dealService.deleteObj(dealInstance)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])}"
            redirect(action: "list")
        }
    }
	
	def listDealsReadyToLaunch = {
		String state = "READY";
		
        render(view: "list", model: [dealInstanceList: dealService.listDealsByState(state), dealInstanceTotal: dealService.listDealsByState(state).count()])

	}
	
	def comprar = {

		
		//si no hay un usuario logueado
		if(!session.user) {
			// i.e. user not logged in
			//redirect(controller:'user',action:'loginPage',params:params)
			redirect(controller:'user',action:'loginPrimerIntento',params:params)
			
			
		}else{
		
			//Deal deal = new Deal()
			//deal.id = params.dealId
			//Deal dealInstance = Deal.get(params.dealId)
			Deal dealInstance = Deal.get(session.deal.id)
			
			Purchase purchase = dealService.comprar(dealInstance,session.user)
			
			
			redirect(controller: "purchase", action: "show", params: [id:purchase.id])
		}


		
	}
	
	def checkUser() {
		if(!session.user) {
			// i.e. user not logged in
			redirect(controller:'user',action:'loginPage',params:params)
		}
	}

	def generateData = {
		
		dealService.crearUnDealCompletoTest()
		
		redirect(controller:'mainview',action:'index')
	}
	
	public void controlarDeal() {
		
		dealService.controlarFechaDeal()
	}
	
}
